package com.example.canvasdemo.ui

import android.content.Intent
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.util.Log
import android.widget.SeekBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.canvasdemo.databinding.ActivityDrawBinding
import com.example.canvasdemo.model.DrawingModel
import com.example.canvasdemo.model.UserModel
import com.example.canvasdemo.model.Word
import com.example.canvasdemo.network.ApiService
import com.example.canvasdemo.network.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


class DrawActivity : AppCompatActivity(), SensorEventListener {
    private lateinit var binding: ActivityDrawBinding
    private lateinit var currentWord: Word
    private var roomId: Long = 0
    private var userName: String = "111"

    private var sensorManager: SensorManager? = null
    private var lightSensor: Sensor? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDrawBinding.inflate(layoutInflater)
        setContentView(binding.root)

        roomId = intent.getLongExtra("room_id", 0L)
        if (roomId == 0L) {
            Toast.makeText(this, "无效的房间ID", Toast.LENGTH_SHORT).show()
            finish() // 结束活动
            return
        }

        fetchNextWord()

        sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        lightSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_LIGHT)

        binding.btnRed.setOnClickListener {
            binding.customCanvas.setColor(Color.RED)
        }
        binding.btnGreen.setOnClickListener {
            binding.customCanvas.setColor(Color.GREEN)
        }
        binding.btnBlue.setOnClickListener {
            binding.customCanvas.setColor(Color.BLUE)
        }
        binding.btnBlack.setOnClickListener {
            binding.customCanvas.setColor(Color.BLACK)
        }

        // 切换到橡皮擦模式
        binding.btnEraser.setOnClickListener {
            binding.customCanvas.enableEraserMode()
        }

        // 恢复到画笔模式
        binding.btnBrush.setOnClickListener {
            binding.customCanvas.disableEraserMode()
        }

        // 调整线条粗细
        binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                binding.customCanvas.setStrokeWidth(progress.toFloat())
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 清空画布
        binding.btnClear.setOnClickListener {
            binding.customCanvas.clearCanvas()
        }

        // 上传绘画
        binding.btnUpload.setOnClickListener {
            uploadDrawing()
        }
    }

    private fun fetchNextWord() {
        // 调用API获取下一个词语
        val apiService = RetrofitClient.instance.create(ApiService::class.java)
        apiService.getWords(1).enqueue(object : Callback<List<Word>> {
            override fun onResponse(call: Call<List<Word>>, response: Response<List<Word>>) {
                if (response.isSuccessful) {
                    val wordList = response.body()
                    if (wordList != null && wordList.isNotEmpty()) {
                        currentWord = wordList[0] // 获取第一个词语
                        binding.tvWord.text = "提示：${currentWord.word}" // 显示词语
                    } else {
                        Toast.makeText(this@DrawActivity, "没有获取到词语", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Toast.makeText(this@DrawActivity, "获取词语失败", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(call: Call<List<Word>>, t: Throwable) {
                Toast.makeText(this@DrawActivity, "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun uploadDrawing() {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val api = RetrofitClient.instance.create(ApiService::class.java)
                val drawingData = binding.customCanvas.getDrawingData() // 获取绘画数据，例如 Base64 编码的图像数据
                val drawingModel = DrawingModel(
                    playerName = userName,
                    drawingData = drawingData,
                    hint = currentWord.hint,
                    id = 6,
                    word = currentWord.word
                )
                // 打印请求体日志
                Log.d("Upload", "Request Body: $drawingModel")

                // 调用上传绘画的 API
                val response = api.uploadDrawing(roomId, drawingModel)

                // 切换到主线程更新 UI
                withContext(Dispatchers.Main) {
                    if (response.isSuccessful) {
                        // 打印响应体内容
                        val uploadResponse = response.body()
                        Log.d("Upload", "Response Body: $uploadResponse")
                        Toast.makeText(this@DrawActivity, "绘画上传成功", Toast.LENGTH_SHORT).show()
                        val intent = Intent(this@DrawActivity, RoomDetailActivity::class.java)
                        intent.putExtra("room_id", roomId)
                        startActivity(intent)
                        finish()
                    } else {
                        // 打印错误响应体
                        val errorBody = response.errorBody()?.string()
                        Log.e("Upload", "Response Failed: $errorBody")

                        Toast.makeText(
                            this@DrawActivity,
                            "绘画上传失败: ${response.message()}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    // 打印异常错误信息
                    Log.e("Upload", "Error: ${e.message}")
                    Toast.makeText(this@DrawActivity, "网络错误: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    // 传感器监听方法
    override fun onSensorChanged(event: SensorEvent?) {
        if (event != null && event.sensor.type == Sensor.TYPE_LIGHT) {
            val lightLevel = event.values[0]
            // 判断亮度是否低于10
            if (lightLevel < 10) {
                // 弹出提示框
                Toast.makeText(this, "环境亮度过低，请爱护眼睛", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
    }

    override fun onResume() {
        super.onResume()
        // 注册光感传感器
        sensorManager?.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_UI)
    }

    override fun onPause() {
        super.onPause()
        // 注销光感传感器监听
        sensorManager?.unregisterListener(this)
    }
}



